<template>
  <div class="app-container">
    <el-row :gutter="20" class="mb8">
      <el-col :span="4" style="border: 2px dashed #ddd; padding: 10px 5px; border-radius: 5px;" >
        <el-row>
          <el-col :span="24">
            <div style="display: flex; justify-content: center">
              <el-button
                type="primary"
                icon="Plus"
                @click="addMaterial"
              ></el-button>
              <el-button
                type="info"
                icon="EditPen"
                @click="editMaterial"
              ></el-button>
              <el-button
                type="danger"
                icon="Delete"
                @click="deleteMaterial"
              ></el-button>
            </div>
            <div style="display: flex; justify-content: center">
              <div style="margin-top: 10%">物料组织树</div>
            </div>
            <div
              style="
                display: flex;
                justify-content: center;
                font-size: 12px;
                color: cornflowerblue;
              "
            >
              <div style="margin-top: 10%">
                当前物料:{{ ShowMaterialName }}-{{ MaterialCode }}
              </div>
            </div>
            <el-tree
              highlight-current
              :default-expand-all="true"
              style="margin-top: 5%"
              :data="treeDate"
              :props="defaultProps"
              @node-click="handleNodeClick"
            />
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="20">
        <el-form :model="queryParams" ref="queryRef" :inline="true">
          <el-form-item label="物料编号" prop="code">
            <el-input
              v-model="queryParams.code"
              placeholder="请输入物料编码"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="物料名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入纸张名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="品牌" prop="brand">
            <el-select
              v-model="queryParams.brand"
              class="m-2"
              placeholder="请选择品牌"
              style="width: 100%"
            >
              <el-option
                v-for="item in mes_material_brand"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              >新增</el-button
            >
            <!-- <div>
                                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                                </div> -->
          </el-form-item>
        </el-form>
        <el-row>
          <el-col :span="24">
            <el-table v-loading="loading" border :data="accessoryList">
              <el-table-column
                label="序号"
                width="60"
                type="index"
                align="center"
              >
              </el-table-column>
              <el-table-column label="状态" align="center" prop="status">
                <template #default="scope">
                  <dict-tag
                    :options="sys_normal_disable"
                    :value="scope.row.status"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="物料编号"
                min-width="180"
                align="center"
                prop="code"
              >
                <template v-slot="{ row }">
                  <el-button link type="primary" @click="handleView(row)">{{
                    row.code
                  }}</el-button>
                </template>
              </el-table-column>
              <el-table-column
                label="物料名称"
                align="center"
                prop="name"
                width="100"
              />
              <el-table-column
                label="物料全称"
                align="center"
                prop="fullName"
                width="100"
              />
              <el-table-column
                label="实时单价"
                align="center"
                prop="realtimePrice"
              />
              <!--                            <el-table-column label="加权单价" align="center" prop="authorityPrice" />-->
              <el-table-column
                label="库存数量"
                align="center"
                prop="quantity"
              />
              <el-table-column
                label="库存金额"
                align="center"
                prop="stockPrice"
              />
              <el-table-column label="物料品牌" align="center" prop="brand">
                <template #default="scope">
                  <dict-tag
                    :options="mes_material_brand"
                    :value="scope.row.brand"
                  />
                </template>
              </el-table-column>
              <el-table-column label="计量单位" align="center" prop="unit">
                <template #default="scope">
                  <dict-tag
                    :options="mes_material_unit"
                    :value="scope.row.unit"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="所属分类"
                align="center"
                prop="belongClassName"
                width="100"
              />
              <!-- <el-table-column label="自有编码" align="center" prop="originalCode" /> -->
              <el-table-column label="规格型号" align="center" prop="specs" />
              <el-table-column
                label="采购专员编码"
                align="center"
                prop="buyerCode"
              />
              <el-table-column
                label="采购专员"
                align="center"
                prop="buyerName"
              />
              <el-table-column label="定量" align="center" prop="weight" />
              <el-table-column label="长度" align="center" prop="longWide" />
              <el-table-column label="宽度" align="center" prop="wide" />
              <el-table-column label="高度" align="center" prop="height" />

              <el-table-column
                label="安全库存"
                align="center"
                prop="safetyStock"
              />
              <el-table-column
                label="最低库存"
                align="center"
                prop="minStock"
              />
              <el-table-column
                label="最高库存"
                align="center"
                prop="maxStock"
              />
              <el-table-column
                label="最初库存"
                align="center"
                prop="originalStock"
              />
              <el-table-column label="所属仓库" align="center" prop="store" />

              <el-table-column
                label="操作"
                fixed="right"
                align="center"
                min-width="150"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-tooltip
                    content="编辑"
                    v-if="scope.row.status == 1"
                    placement="top"
                  >
                    <el-button
                      link
                      type="primary"
                      icon="Edit"
                      @click="handleEdit(scope.row)"
                    ></el-button>
                  </el-tooltip>
                  <el-tooltip
                    content="删除"
                    v-if="scope.row.status == 1"
                    placement="top"
                  >
                    <el-button
                      link
                      type="primary"
                      icon="Delete"
                      @click="handleDle(scope.row)"
                    ></el-button>
                  </el-tooltip>

                  <el-button
                    link
                    type="primary"
                    icon="TurnOff"
                    @click="handleServe(scope.row)"
                    >{{ scope.row.status == 0 ? "停用" : "启用" }}</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <pagination
              style="margin-top: 0; padding-top: 0"
              v-show="total > 0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <el-dialog v-model="dialogFormVisible" :title="title" width="40%">
      <el-form :model="form">
        <el-form-item label="物料名称" label-width="150px">
          <el-input v-model="materialName" style="width: 300px" />
        </el-form-item>
        <el-form-item label="上级节点" label-width="150px">
          <el-tree-select
            style="width: 300px"
            v-model="choicePid"
            :data="fathertreeDate"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            @node-click="handleChange"
            value-key="id"
            check-strictly
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUp"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="customer">
import {
  listMaterialclass,
  addMaterialclass,
  getMaterialclass,
  updateMaterialclass,
  delMaterialclass,
  delMaterial,
  listMaterial,
  changeMesMaterialStatus,
} from "@/api/basicInfo/accessory.js";
const { proxy } = getCurrentInstance();
const {
  mes_material_brand,
  mes_material_unit,
  sys_normal_disable,
  mes_material_specs,
} = proxy.useDict(
  "mes_material_brand",
  "mes_material_unit",
  "sys_normal_disable",
  "mes_material_specs"
);
import useTagsViewStore from "@/store/modules/tagsView";
const tagsViewStore = useTagsViewStore();
import { ElMessage, ElMessageBox, useDelayedRender } from "element-plus";
const router = useRouter();
const route = useRoute();
const accessoryList = ref([]);
const treeDate = ref([]);
const fathertreeDate = ref([]);

const loading = ref(false);
const total = ref(0);

const MaterialCode = ref("");
const ShowMaterialName = ref("");
const MaterialId = ref("");
const title = ref("");

const dialogFormVisible = ref(false);
const addBefore = ref(null);
const choicePid = ref(0);
const materialName = ref("");
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    code: null,
    name: null,
    id: null,
  },
  rules: {
    code: [{ required: true, message: "客户编码不能为空", trigger: "blur" }],
    name: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
  },
});
const { queryParams, form, rules } = toRefs(data);

const defaultProps = {
  children: "children",
  // label: 'name',
  label: (node) => `${node.name} - ${node.code}`,
};

if (route.query?.materialCode) {
  queryParams.value.code = route.query.materialCode;
  listMaterial(queryParams.value).then((res) => {
    if (res.rows.length > 0) {
      tagsViewStore.delView(route);
      setTimeout(() => {
        handleView(res.rows[0]);
      }, 0);
    }
  });
} else {
  getList();
}
const CodeTree = async () => {
  try {
    const response = await listMaterialclass();
    treeDate.value = response.data;
  } catch (error) {
    console.error("Error", error);
  }
};
const treeToMultiArray = (treeData) => {
  const result = [];
  const map = new Map();
  treeData.forEach((item) => {
    map.set(item.id, item);
    item.children = [];
  });
  treeData.forEach((item) => {
    // 如果 pid 为 0，说明是根节点
    if (item.pid === 0) {
      result.push(item);
    } else {
      // 如果 pid 不为 0，将当前节点放入对应的父节点children 中
      const parent = map.get(item.pid);
      if (parent) {
        parent.children.push(item);
      }
    }
  });
  return result;
};
(async () => {
  await CodeTree();
  const multiArray = treeToMultiArray(treeDate.value);
  treeDate.value = multiArray;
  fathertreeDate.value = [
    { name: "根节点", pid: 0, id: 0, children: [...treeDate.value] },
  ];
})();

const handleChange = (value) => {
  console.log("Selected value:", value);
};
const handleNodeClick = (data) => {
  ShowMaterialName.value = data.name;
  MaterialCode.value = data.code;
  MaterialId.value = data.id;
  queryParams.value.id = data.id;
  choicePid.value = data.id;
  addBefore.value = data;
  getList();
};
const addMaterial = () => {
  title.value = "新增物料";
  materialName.value = undefined;
  // choicePid.value = Number(0)
  dialogFormVisible.value = true;
};
const editMaterial = () => {
  if (!MaterialId.value) {
    return ElMessage({
      message: "请先选择一个物料",
      type: "warning",
    });
  } else {
    getMaterialclass(MaterialId.value).then((response) => {
      console.log("response", response);
      title.value = "编辑物料";
      materialName.value = response.data.name;
      choicePid.value = Number(response.data.pid);
      dialogFormVisible.value = true;
    });
  }
};
const deleteMaterial = async () => {
  try {
    await ElMessageBox.confirm("确定要删除选择的物料的信息吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 用户点击了确定按钮
    const response = await delMaterialclass(MaterialId.value);
    if (response.code === 200) {
      ShowMaterialName.value = "";
      MaterialCode.value = "";
      MaterialId.value = "";
      queryParams.value.id = "";
      choicePid.value = Number(0);
      addBefore.value = "";

      ElMessage({
        message: "删除成功",
        type: "success",
      });
      // 在异步函数中使用 await 等待 CodeTree 的执行完成
      await CodeTree();

      const multiArray = treeToMultiArray(treeDate.value);
      treeDate.value = multiArray;
      fathertreeDate.value = [
        { name: "根节点", pid: 0, id: 0, children: [...treeDate.value] },
      ];
    }
  } catch (error) {
    console.error("发生错误:", error);
    // 处理异常
  }
};

const showMessage = (message, type) => {
  ElMessage({
    message,
    type,
  });
};
const handleSuccessResponse = async (response, message) => {
  if (response.code === 200) {
    showMessage(message, "success");
    ShowMaterialName.value = "";
    MaterialCode.value = "";
    MaterialId.value = "";
    choicePid.value = Number(0);
    queryParams.value.id = "";
    addBefore.value = "";
    await CodeTree();
    treeDate.value = treeToMultiArray(treeDate.value);
    fathertreeDate.value = [
      { name: "根节点", pid: 0, id: 0, children: [...treeDate.value] },
    ];
    dialogFormVisible.value = false;
  }
};
const handleUp = async () => {
  try {
    if (choicePid.value != null && materialName.value) {
      if (title.value === "新增物料") {
        const response = await addMaterialclass({
          name: materialName.value,
          pid: choicePid.value,
        });
        await handleSuccessResponse(response, "新增物料节点成功");
      } else {
        //编辑
        const response = await updateMaterialclass({
          name: materialName.value,
          pid: choicePid.value,
          id: addBefore.value.id,
        });
        if (response.code === 200) {
          await handleSuccessResponse(response, "编辑物料节点成功");
        }
      }
    } else {
      showMessage("请填写物料名称并选择上级节点", "warning");
    }
  } catch (error) {
    console.log("error", error);
    if (error.message === "该分类项包含物料信息暂不支持编辑") {
      console.log("该分类项包含物料信息暂不支持编辑");
      // 执行特定的操作
    } else {
      // 其他错误的处理逻辑
      console.error("Error during handleUp:", error);
      showMessage("操作失败，请稍后重试", "error");
    }
    dialogFormVisible.value = false;
  }
};

// 新增
const handleAdd = () => {
  if (!MaterialCode.value) {
    return ElMessage({
      message: "请先选择一个物料",
      type: "warning",
    });
  }
  if (addBefore.value.children.length != 0) {
    return ElMessage({
      message: "请选择末级节点 进行新增",
      type: "warning",
    });
  }
  router.push({
    path: "/basicInfo/accessory/details",
    query: {
      MaterialName: ShowMaterialName.value,
      MaterialCode: MaterialCode.value,
    },
  });
};
// 查看
const handleView = (row) => {
  router.push({
    path: "/basicInfo/accessory/details",
    query: {
      id: row.id,
      readonly: true,
      status: row.status,
      code: row.code,
    },
  });
};
const handleEdit = (row) => {
  router.push({
    path: "/basicInfo/accessory/details",
    query: {
      id: row.id,
      status: row.status,
      code: row.code,
    },
  });
};
//停用启用
const handleServe = (row) => {
  const state = row.status === 0 ? "1" : "0";
  const stateText = row.status === 0 ? "停用" : "启用";
  ElMessageBox.confirm(
    `确定要 ${stateText} 物料名称为 ${row.name} 的信息吗?`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    // 用户点击了确定按钮
    row.status = state;
    changeMesMaterialStatus(row.id, state).then((response) => {
      if (response.code === 200) {
        ElMessage({
          message: `${stateText}成功`,
          type: "success",
        });
        getList();
      }
    });
  });
};

//删除
const handleDle = (row) => {
  ElMessageBox.confirm(
    "确定要删除物料名称为 " + row.name + " 的信息吗?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      // 用户点击了确定按钮
      delMaterial(row.id).then((response) => {
        if (response.code === 200) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });

          getList();
        }
      });
    })
    .catch(() => {
      //取消
    });
};
function getList() {
  loading.value = true;
  listMaterial(queryParams.value)
    .then((response) => {
      accessoryList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
    });
}
/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.code = null;
  queryParams.value.name = null;
  queryParams.value.brand = null;
  queryParams.value.id = null;

  handleQuery();
}

getList();
</script>

<style scoped>
/* ::v-deep .el-button+.el-button {
    margin-left: 2px
} */
</style>